<template>
  <div class="app-container">
    <el-form ref="dialogForm" :model="formData">
      <div style="display: flex; margin-bottom: 10px">
        <div class="commonclass">
          <div v-if="activeTitle == '依赖配置'" style="margin-top: 6px">
            文件名：
            {{ formData.name }}
          </div>
          <div v-else style="display: flex; align-items: center">
            <div style="width: 100px">文件名:</div>
            <el-select
              v-model="fileNameId"
              placeholder="请选择文件名"
              @change="handlechangId"
            >
              <el-option
                v-for="item in tablechangeLists"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </div>
        </div>
        <div class="commonclass">
          <div v-if="['项目配置', '其他配置'].includes(activeTitle)">
            文件路径：{{ formData.pathInProject }}
          </div>
          <div v-else style="display: flex; align-items: center">
            <div style="width: 100px">文件路径：</div>
            <el-select
              v-model="fileNameId"
              placeholder="请选择文件路径"
              @change="handlechangId"
            >
              <el-option
                v-for="item in tablechangeLists"
                :key="item.id"
                :label="item.pathInProject"
                :value="item.id"
              />
            </el-select>
          </div>
        </div>
        <div class="commonclass" style="display: flex; align-items: center">
          <span style="width: 100px">展示名称：</span>
          <el-input v-model.trim="viewName" placeholder="" clearable />
        </div>
        <div class="commonclass" style="display: flex; align-items: center">
          <span style="width: 60px">描述：</span>
          <el-input v-model.trim="description" placeholder="" clearable />
        </div>
      </div>
      <el-form-item
        prop="content"
        label="文件内容"
        v-if="activeTitle != '依赖配置'"
      >
        <div style="display: inline-block; margin-bottom: 5px">
          <span class="split">|</span>
          <el-dropdown @command="changeCodeTheme">
            <span class="el-dropdown-link">
              代码样式<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-for="(item, index) in codeThemeList"
                :command="item"
                :key="index"
                >{{ item }}</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
          <span class="split">|</span>
          快捷键：<el-tag
            v-for="(item, index) in shortcutKeyList"
            effect="plain"
            size="mini"
            style="margin-right: 5px"
            :key="index"
            >{{ item }}</el-tag
          >
        </div>
        <div class="pointerEvents">
          <codemirror
            ref="editor"
            v-model="formData.content"
            :options="cmOptions"
          />
        </div>
      </el-form-item>
      <div v-else>
        <div style="margin-bottom: 10px">
          <el-button type="primary" @click="handleAddyilai">添加依赖</el-button>
          <el-button type="primary" @click="handleDelete">删除依赖</el-button>
          <el-button type="primary">添加属性</el-button>
          <el-button type="primary">删除属性</el-button>
        </div>
        <codemirror
          ref="editor"
          v-model="formData.content"
          :options="cmOptions"
        />
      </div>
    </el-form>
    <span slot="footer" class="dialog-footer" style="text-align: center">
      <div v-if="activeTitle == '依赖配置'">
        <!-- <el-button type="primary" @click="onSave">保存且更新依赖</el-button> -->
      </div>

      <div v-else style="padding-left: 38px">
        <el-button type="primary" @click="onSave">保存</el-button>
        <el-button type="primary" @click="onSave">发布</el-button>
      </div>
    </span>
    <el-dialog
      title="添加依赖"
      :visible.sync="diaVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form ref="addForm" :model="addForm">
        <el-form-item
          prop="groupId"
          label="groupId"
          :rules="[
            {
              required: true,
              message: '请输入groupId',
              trigger: 'blur',
            },
          ]"
        >
          <el-input v-model.trim="addForm.groupId" clearable />
        </el-form-item>
        <el-form-item
          prop="artifactId"
          label="artifactId"
          :rules="[
            {
              required: true,
              message: '请输入artifactId',
              trigger: 'blur',
            },
          ]"
        >
          <el-input v-model.trim="addForm.artifactId" clearable />
        </el-form-item>
        <el-form-item
          prop="version"
          label="version"
          :rules="[
            {
              required: true,
              message: '请输入version',
              trigger: 'blur',
            },
          ]"
        >
          <el-input v-model.trim="addForm.version" clearable />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="diaVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSave" :loading="loading"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      title="删除依赖"
      :visible.sync="deleteVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form ref="deleteForm" :model="deleteForm">
        <el-form-item
          label="选择"
          prop="multipleChoice"
          :rules="[
            {
              validator: this.validatePass,
              trigger: 'change',
            },
          ]"
        >
          <el-select
            v-model="deleteForm.multipleChoice"
            multiple
            filterable
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in deleteLists"
              :key="item.id"
              :label="item.descLabel"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleBtnDelete">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<style>
.el-form-item--mini .el-form-item__content,
.el-form-item--mini .el-form-item__label,
.el-form-item__content {
  line-height: 20px;
}
.velocity-tip {
  color: #606266;
  font-size: 13px;
  font-weight: normal;
}
.velocity-var {
}
.velocity-var li {
  font-size: 14px;
  color: #606266;
  line-height: 26px;
}
.velocity-var a {
  color: #409eff;
  font-weight: 500;
}
.velocity-var a:hover {
  color: rgba(64, 158, 255, 0.75);
}
.hasFix {
  position: fixed;
  top: 0;
}
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}
.el-icon-arrow-down {
  font-size: 12px;
}
span.split {
  color: #ccc;
  margin: 0 3px;
}
</style>

<script>
import {
  projectConfigupdate,
  projectConfigfindPage,
  projectManageProjectConfigInfo,
} from "@/api/article";
import { codemirror } from "vue-codemirror";

import "codemirror/theme/neat.css";
import "codemirror/theme/darcula.css";
import "codemirror/theme/material.css";

/** 搜索 替换框置顶*/
import "codemirror/addon/scroll/annotatescrollbar.js";
import "codemirror/addon/search/matchesonscrollbar.js";
import "codemirror/addon/search/match-highlighter.js";
import "codemirror/addon/search/jump-to-line.js";

import "codemirror/addon/dialog/dialog.js";
import "codemirror/addon/dialog/dialog.css";
import "codemirror/addon/search/searchcursor.js";
import "codemirror/addon/search/search.js";

require("codemirror/mode/velocity/velocity");

import "codemirror/theme/ambiance.css";
import "codemirror/lib/codemirror.css";
import "codemirror/addon/hint/show-hint.css";
require("codemirror/addon/edit/matchbrackets");
require("codemirror/addon/selection/active-line");
require("codemirror/mode/sql/sql");
require("codemirror/addon/hint/show-hint");
require("codemirror/addon/hint/sql-hint");
require("codemirror/mode/clike/clike.js");
require("codemirror/addon/edit/closebrackets.js");

const TEMPLATE_CODE_THEME = "gen.template.code.theme";
import {
  pomAddDependency,
  pomListDependency,
  pomDeleteDependency,
} from "@/api/lowcode";
export default {
  name: "configurationessEdit",
  components: { codemirror },
  props: {
    dialogVisible: {
      type: Boolean,
      default: false,
    },
    editId: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      viewName: "",
      description: "",
      deleteLists: [],
      deleteForm: {
        projectId: +sessionStorage.getItem("developLowCodeId"),
        multipleChoice: [],
      },
      deleteVisible: false,
      loading: false,
      diaVisible: false,
      addForm: {
        projectId: +sessionStorage.getItem("developLowCodeId"),
      },
      fileNameId: "",
      activeTitle: sessionStorage.getItem("activeState"),
      full_screen: false,
      codeThemeList: ["neat", "darcula", "material"],
      shortcutKeyList: [
        "保存(Ctrl+S)",
        "删除当行(Ctrl+D)",
        "复制当行(Ctrl+C)",
        "剪切当行(Ctrl+X)",
        "替换(Ctrl+Shift+F)",
      ],
      formData: {},
      formRules: {
        // viewName: [{ required: true, message: "不能为空", trigger: "blur" }],
        // description: [{ required: true, message: "不能为空", trigger: "blur" }],
        content: [{ required: true, message: "不能为空", trigger: "blur" }],
      },
      //code mirror配置
      cmOptions: {
        value: "",
        // mode: 'text/velocity',
        mode: "text/x-java",
        theme: "neat",
        lineNumbers: true,
        readOnly: false,
        tabSize: 4, // tab的空格个数
        indentUnit: 2, // 一个块（编辑语言中的含义）应缩进多少个空格
        autocorrect: true, // 自动更正
        spellcheck: true, // 拼写检查
        lint: true, // 检查格式
        lineNumbers: true, //是否显示行数
        lineWrapping: true, //是否自动换行
        styleActiveLine: true, //line选择是是否高亮
        // keyMap: 'intellij',  // sublime编辑器效果
        matchBrackets: true, //括号匹配
        autoCloseBrackets: true, // 在键入时将自动关闭括号和引号
        matchTags: { bothTags: true }, // 将突出显示光标周围的标签
        foldGutter: true, // 可将对象折叠，与下面的gutters一起使用
        gutters: [
          "CodeMirror-lint-markers",
          "CodeMirror-linenumbers",
          "CodeMirror-foldgutter",
        ],
        highlightSelectionMatches: {
          minChars: 2,
          style: "matchhighlight",
          showToken: true,
        },
        hintOptions: {
          // 自定义提示选项
          completeSingle: false, // 当匹配只有一项的时候是否自动补全
          tables: {}, // 代码提示
        },
      },
      isVelocityBarFixed: false,
      // tree
      collapseActiveName: "0",
      needFix: false,
      keywordHelpShow: false,
      tablechangeLists: [],
    };
  },
  async created() {
    //初始化代码主题
    this.cmOptions.theme = this.getAttr(TEMPLATE_CODE_THEME) || "neat";
    this.activeTitle = sessionStorage.getItem("activeState");
    await this.projectConfigfindPage(
      +sessionStorage.getItem("developLowCodeId")
    );
    if (this.activeTitle == "依赖配置") {
      this.tablechangeLists = this.tableData.filter((item) =>
        item.name.startsWith("pom")
      );
    } else if (this.activeTitle == "项目配置") {
      this.tablechangeLists = this.tableData.filter((item) =>
        item.name.startsWith("application")
      );
    } else if (this.activeTitle == "其他配置") {
      this.tablechangeLists = this.tableData.filter(
        (item) =>
          !item.name.startsWith("pom") && !item.name.startsWith("application")
      );
    }
    if (this.tablechangeLists.length) {
      const list = this.tablechangeLists[0];
      this.fileNameId = list.id;
      // this.formData = JSON.parse(JSON.stringify(list));
      await this.projectManageProjectConfigInfo(this.fileNameId);
      this.viewName = this.formData.viewName;
      this.description = this.formData.description;
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs.editor.codemirror.on("inputRead", (cm, event) => {
        const index = this.formData.name.lastIndexOf(".");
        const code = this.formData.name.slice(index);
        if (code === ".java") {
          if (/^[a-zA-Z\.=]$/gi.test(event.text[0])) {
            cm.showHint();
          }
        }
      });
    });
    window.addEventListener("scroll", this.handlerScroll);
    this.watchKeydown();
  },
  methods: {
    validatePass(rule, value, callback) {
      if (value.length === 0) {
        callback(new Error("请选择内容"));
      } else {
        callback();
      }
    },
    async pomListDependency(date) {
      const res = await pomListDependency(date);
      if (res?.code === 200) {
        this.deleteLists = JSON.parse(JSON.stringify(res.data));
        this.deleteLists.forEach((item) => {
          this.$set(
            item,
            "descLabel",
            `${item.groupId}|${item.artifactId}|${item.version}`
          );
        });
        this.deleteForm.multipleChoice = [this.deleteLists[0]?.id];
      } else {
        this.deleteLists = [];
        this.deleteForm.multipleChoice = [];
      }
    },
    async projectManageProjectConfigInfo(id) {
      const res = await projectManageProjectConfigInfo(id);
      if (res?.code === 200) {
        this.formData = res.data;
      } else {
        this.formData = {};
      }
    },
    async projectConfigfindPage(id) {
      this.tableData = [];
      const res = await projectConfigfindPage(id);
      if (res?.code === 200) {
        this.tableData = res.data;
      } else {
        this.tableData = [];
      }
    },
    handlechangId(id) {
      this.projectManageProjectConfigInfo(id);
    },
    refresh() {
      this.jsonEditor && this.jsonEditor.refresh();
    },
    watchKeydown() {
      let _this = this;
      document.onkeydown = function (e) {
        let key = window.event.keyCode;
        if (key == 83 && event.ctrlKey) {
          //s == 83 && event.ctrlKey
          window.event.preventDefault(); //关闭浏览器快捷键
          // _this.onSave();
        }
        if (event.ctrlKey && key == 82) {
          window.event.preventDefault(); //关闭浏览器快捷键
        }
      };
    },
    handlerScroll() {
      const scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      this.needFix = scrollTop > 80;
    },
    async onSave() {
      this.formData.viewName = this.viewName;
      this.formData.description = this.description;
      const res = await projectConfigupdate(this.formData);
      if (res?.code === 200) {
        this.$message({
          message: "编辑成功",
          type: "success",
        });
        this.projectManageProjectConfigInfo(this.fileNameId);
      }
    },
    handleAddyilai() {
      this.diaVisible = true;
      this.addForm = {
        projectId: +sessionStorage.getItem("developLowCodeId"),
      };
    },
    handleDelete() {
      this.deleteVisible = true;
      this.pomListDependency({
        projectId: +sessionStorage.getItem("developLowCodeId"),
        pomFilePath: this.formData.path,
      });
    },
    handleBtnDelete() {
      console.log(this.deleteForm.multipleChoice, 123456);
      this.$refs["deleteForm"].validate((valid) => {
        if (valid) {
          this.$confirm(`删除依赖可能会导致代码编译报错，请谨慎操作`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(async () => {
            const deleteLists = this.deleteForm.multipleChoice.reduce(
              (pre, next) => {
                const obj = this.deleteLists.find((item) => item.id == next);
                if (obj) {
                  pre.push({
                    groupId: obj.groupId,
                    artifactId: obj.artifactId,
                    version: obj.version,
                  });
                }
                return pre;
              },
              []
            );
            const res = await pomDeleteDependency({
              pomFilePath: this.formData.path,
              projectId: +sessionStorage.getItem("developLowCodeId"),
              delete: deleteLists,
            });
            if (res?.code === 200) {
              this.deleteVisible = false;
              this.$message({
                message: "删除成功",
                type: "success",
              });
              this.projectManageProjectConfigInfo(this.fileNameId);
            }
          });
        }
      });
    },
    handleSave() {
      console.log(this.formData, 133045);
      this.$refs["addForm"].validate(async (valid) => {
        if (valid) {
          this.loading = true;
          this.addForm.pomFilePath = this.formData.path;
          try {
            const res = await pomAddDependency(this.addForm);
            if (res?.code === 200) {
              this.diaVisible = false;
              this.$message({
                message: "保存成功",
                type: "success",
              });
              this.projectManageProjectConfigInfo(this.fileNameId);
            }
          } finally {
            this.loading = false;
          }
        }
      });
    },
    changeCodeTheme(theme) {
      this.cmOptions.theme = theme;
      this.setAttr(TEMPLATE_CODE_THEME, theme);
    },
  },
};
</script>
<style scoped lang="scss">
::v-deep .CodeMirror {
  height: inherit !important;
  border: 1px solid #eee !important;
}
.pointerEvents {
  ::v-deep .CodeMirror-wrap {
    pointer-events: auto;
  }
  .vue-codemirror {
    max-height: calc(-262px + 100vh);
  }
}
::v-deep .vue-codemirror {
  max-height: calc(-240px + 100vh);
  overflow: auto;
}
.isfullscreen {
  position: absolute;
  right: 50px;
  top: 15px;
}
.commonclass {
  margin-right: 20px;
}
::v-deep .CodeMirror-wrap {
  pointer-events: none;
}
</style>
